package co.yixiang.modules.shop.rest;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.constant.ShopConstants;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.BillEnum;
import co.yixiang.modules.activity.domain.YxStoreCombination;
import co.yixiang.modules.activity.domain.YxStoreSeckill;
import co.yixiang.modules.activity.service.YxStoreCombinationService;
import co.yixiang.modules.activity.service.YxStorePinkService;
import co.yixiang.modules.activity.service.YxStoreSeckillService;
import co.yixiang.modules.order.domain.YxStoreOrder;
import co.yixiang.modules.order.service.YxStoreOrderCartInfoService;
import co.yixiang.modules.order.service.YxStoreOrderService;
import co.yixiang.modules.product.domain.YxCommissionDetail;
import co.yixiang.modules.product.domain.YxCommissionType;
import co.yixiang.modules.product.domain.YxStoreProduct;
import co.yixiang.modules.product.service.YxCommissionDetailService;
import co.yixiang.modules.product.service.YxCommissionTypeService;
import co.yixiang.modules.product.service.YxStoreProductService;
import co.yixiang.modules.shop.domain.YxSystemUserLevel;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.template.domain.YxSystemCity;
import co.yixiang.modules.template.service.YxSystemCityService;
import co.yixiang.modules.user.domain.MonthlyManagementAwardDetail;
import co.yixiang.modules.user.domain.YxSystemUserTask;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "分润方法", tags = "返佣:分润", description = "分润")
public class CommissionNewController {
    //private  YxUserServiceImpl yxUserService;
    @Autowired
    private final YxUserService yxUserService;
    private final YxUserLevelService yxUserLevelService;
    private final YxStoreOrderService storeOrderService;
    private final YxStoreOrderCartInfoService storeOrderCartInfoService;
    private final YxUserBillService yxUserBillService;
    private final AreaService areaService;
    private final YxStoreCombinationService storeCombinationService;
    private final YxStorePinkService storePinkService;
    private final YxSystemCityService systemCityService;
    private final YxStoreProductService productService;
    private final YxStoreSeckillService yxStoreSeckillService;
    private final YxCommissionDetailService yxCommissionDetailService;
    private final YxCommissionTypeService yxCommissionTypeService;
    private final YxSystemUserLevelService yxSystemUserLevelService;
    private final YxSystemUserTaskService yxSystemUserTaskService;
    private final YxSystemConfigService systemConfigService;
    private final MonthlyManagementAwardDetailService monthlyManagementAwardDetailService;

    // 新建用户更新上级用户数据
    public void updateParentUserCount(String user_id) {
        log.info("user_id====="+user_id);

        //YxUser user = yxUserService.getById(Long.valueOf(user_id));
        String userId =user_id.split(",")[0];
        String spreadId =user_id.split(",")[1];
        log.info("user====="+userId);
        log.info("spreadId====="+spreadId);
        yxUserService.initPath(Long.valueOf(userId),spreadId);
        log.info("user11111111====="+userId);
        /*JSONObject parentUsers = yxUserService.getParentUsers(Long.valueOf(user_id));
        log.info("parentUsers====="+parentUsers);
        Map<Integer,String> checkMap = new HashMap();
        int i = 1;
        Set<String> keySet= parentUsers.keySet();
        for (String key : keySet) {
            //String key = it.next().toString();
            JSONObject item = parentUsers.getJSONObject(key);
            //int member_level = item.getInteger("level");
            int under_count =  item.getInteger("spread_count");
            int normal_count =  item.getInteger("normal_count");
            int vip_count =  item.getInteger("vip_count");
            if(i==1) {
                under_count++;
            }
            i++;
            YxUser yxUser = yxUserService.getById(Long.valueOf(item.getString("id")));
            yxUser.setSpreadCount(under_count);
            yxUser.setNormalCount(normal_count+1);
            yxUser.setVipCount(vip_count);
            yxUserService.updateById(yxUser);
        }*/

    }

    // 判断购买产品类型，确定分佣方式
    public  void checkOrderGoodsclass(String orderid) {
        System.out.println("orderid==========="+orderid);
        JSONObject jsonObj = storeOrderCartInfoService.getGoodsclassByOrderid(Long.valueOf(orderid));
        //String gc_id = jsonObj.getString("gc_id");
        String goods_id = jsonObj.getString("goods_id");
        String user_id = jsonObj.getString("user_id");
        String member_level = jsonObj.getString("member_level");
        double price = jsonObj.getDouble("price");
        double totalPrice = jsonObj.getDouble("totalPrice");
        int  amount = jsonObj.getInteger("count");
        String payment_id = jsonObj.getString("payment_id");
        String combinationId = jsonObj.getString("combinationId");
        String seckillId = jsonObj.getString("seckillId");
        String isFree =jsonObj.getString("isFree");
        int checkOrderCount = yxUserBillService.checkCommission4order(Long.valueOf(orderid));
        System.out.println("orderid11111111111==========="+orderid);
        if(checkOrderCount ==0){
            if(Long.valueOf(combinationId).intValue()>0){//推三返一
                if("yue".equals(payment_id) || "balanceSum".equals(payment_id)){
                    yueRebateOrderCommission(user_id, goods_id, combinationId,orderid);
                }else{
                    rebateOrderCommission(user_id, goods_id, combinationId,orderid);
                }
            }else if(Long.valueOf(seckillId).intValue()>0){//秒杀
                if("yue".equals(payment_id) || "balanceSum".equals(payment_id)){
                    yueSeckillOrderCommission(user_id, goods_id, seckillId,orderid,amount);
                }else{
                    seckillOrderCommission(user_id, goods_id, seckillId,orderid,amount);
                }
            }else {
                    /*if("true".equals(isFree)){
                        yePayPostageOrderCommission(user_id, goods_id, member_level,orderid,amount,totalPrice,payment_id);
                    }else{
                    }*/
                orderCommission(orderid,jsonObj);
            }
        }

        System.out.println("orderid2222222222222==========="+orderid);
    }

    private  void orderCommission(String orderid,JSONObject jsonObj) {
        String goods_id = jsonObj.getString("goods_id");
        String user_id = jsonObj.getString("user_id");
        String member_level = jsonObj.getString("member_level");
        double price = jsonObj.getDouble("price");
        double payPrice = jsonObj.getDouble("totalPrice");
        int  amount = jsonObj.getInteger("count");
        String payment_id = jsonObj.getString("payment_id");
        String combinationId = jsonObj.getString("combinationId");
        String seckillId = jsonObj.getString("seckillId");
        String isFree =jsonObj.getString("isFree");
        int  operateAmount = jsonObj.getInteger("operateAmount");
        Long  commissionTypeId = jsonObj.getLong("commissionTypeId");//分润类型
        int  isThroughTrain = jsonObj.getInteger("isThroughTrain");//是否直通车

        JSONObject commissionSetting = new JSONObject();// 分润配置
        YxCommissionType type =yxCommissionTypeService.getById(commissionTypeId);
        int isSpecialCommission =type.getIsSpecialCommission();//是否特殊分润
        List<YxCommissionDetail> yxCommissionDetailList=yxCommissionDetailService.list(new LambdaQueryWrapper<YxCommissionDetail>().eq(YxCommissionDetail ::getCommissionTypeId,commissionTypeId));
        log.info("yxCommissionDetailList=====" + yxCommissionDetailList);
        if(yxCommissionDetailList.size()>0){
            for(int i =0;i<yxCommissionDetailList.size();i++){
                YxCommissionDetail detail =yxCommissionDetailList.get(i);
                commissionSetting.put(detail.getLevel().toString(),detail.getValue().toString());
            }
        }
        YxStoreOrder order =storeOrderService.getById(orderid);
        log.info("订单总金额=========="+order.getTotalPrice());
        log.info("commissionSetting=====" + commissionSetting);
        YxStoreProduct product =productService.getById(Long.valueOf(goods_id));
        Map<String, String> team_com_commissionmap = new HashMap();
        Map<String, String> team_com_pjmap = new HashMap();//
        //BigDecimal mainCommissionSum =new BigDecimal("0");
        Map<String, String> mainMap = new HashMap();//购买者分润金额集合
        Map<String, String> bossMap = new HashMap();//
        //运营中心分润
        if(product.getIsPartInFenrun() ==1){
            String operateProvince =systemConfigService.getData(ShopConstants.OPERATE_PROVINCE);//省级
            String operateCity =systemConfigService.getData(ShopConstants.OPERATE_CITY);//市级
            String operateCounty =systemConfigService.getData(ShopConstants.OPERATE_COUNTY);//区级
            BigDecimal provinceBigDecimal =new BigDecimal(operateProvince).multiply(new BigDecimal(product.getOperateAmount())).multiply(new BigDecimal(amount));
            BigDecimal cityBigDecimal =new BigDecimal(operateCity).multiply(new BigDecimal(product.getOperateAmount())).multiply(new BigDecimal(amount));
            BigDecimal countyBigDecimal =new BigDecimal(operateCounty).multiply(new BigDecimal(product.getOperateAmount())).multiply(new BigDecimal(amount));
            operateCommissionUpdate(orderid,provinceBigDecimal,cityBigDecimal,countyBigDecimal);
        }
        int pjSum =0;
        //查找股东分润详情
        YxCommissionDetail topDetail =null;
        if(yxCommissionDetailList.size()>0){
            for(YxCommissionDetail detail:yxCommissionDetailList){
                if(detail.getLevel()==3){
                    topDetail =detail;
                }
            }
        }
        if(!"true".equals(isFree)){
            if (product.getIsVip() != 1) {

                for (int i = 0; i < amount; i++) {
                    JSONObject main = new JSONObject();
                    int orderCount = i + 1;
                    int singular = product.getSingular()*orderCount;
                    YxUser user = yxUserService.getById(Long.valueOf(user_id));
                    main.put("id", user_id);
                    main.put("member_level", user.getLevel());
                    int index = 1;
                    int level = 2;
                    JSONObject parentUsers = yxUserService.getParentUsers(Long.valueOf(user_id));
                    Map<String, String> team_com_map = new HashMap();
                    userCommission4vipMainUpdate(main, index, commissionSetting,
                            team_com_map, orderid, amount, team_com_commissionmap, team_com_pjmap, pjSum, mainMap, product.getLevelAmount(),isSpecialCommission,yxCommissionDetailList,order.getTotalPrice(),topDetail);

                    Set<String> keySet = parentUsers.keySet();
                    log.info("parentUsers=====" + parentUsers);
                    for (String key : keySet) {
                        //String key = it.next().toString();
                        JSONObject item = parentUsers.getJSONObject(key);
                /*item.put("id", item.get("id").toString());
                item.put("member_level", item.get("member_level").toString());*/
                        String memberLevel = item.get("member_level").toString();
                        log.info("memberLevel=====" + memberLevel);
                        int mLevel = 0;
                        if (!isEmpty(memberLevel)) {
                            mLevel = Integer.parseInt(memberLevel);
                        }
                        log.info("mLevel=====" + mLevel);
                        log.info("level=====" + level);
                        log.info("userlevel=====" + user.getLevel());

                        index++;
                    }

                }
            } else {
                for (int i = 0; i < amount; i++) {
                    JSONObject main = new JSONObject();
                    int orderCount = i + 1;
                    int singular = product.getSingular()*orderCount;
                    YxUser user = yxUserService.getById(Long.valueOf(user_id));
                    main.put("id", user_id);
                    main.put("member_level", user.getLevel());
                    int index = 1;
                    int level = 2;
                    JSONObject parentUsers = yxUserService.getParentUsers(Long.valueOf(user_id));
                    Map<String, String> team_com_map = new HashMap();
                    userCommission4vipMainUpdate(main, index, commissionSetting,
                            team_com_map, orderid, amount, team_com_commissionmap, team_com_pjmap, pjSum, mainMap, product.getLevelAmount(),isSpecialCommission,yxCommissionDetailList,order.getTotalPrice(),topDetail);
                    if (!"Y".equals(user.getWhetherVipSlim())) {
                        if (orderCount == amount) {
                            user = yxUserService.getById(Long.valueOf(user_id));
                            user.setWhetherVipSlim("Y");
                            user.setVipDate(new Date());
                            yxUserService.updateById(user);
                        }
                    }
                    if (isThroughTrain != 0) {
                        user = yxUserService.getById(Long.valueOf(user_id));
                        user.setIsThrough("Y");
                        user.setVipHroughTrain(user.getVipHroughTrain() + product.getVipHroughTrain());
                        user.setGoldHroughTrain(user.getGoldHroughTrain() + product.getGoldHroughTrain());
                        user.setDiamondsHroughTrain(user.getDiamondsHroughTrain() + product.getDiamondsHroughTrain());
                        yxUserService.updateById(user);
                    }
                    Set<String> keySet = parentUsers.keySet();
                    log.info("parentUsers=====" + parentUsers);
                    for (String key : keySet) {
                        //String key = it.next().toString();
                        JSONObject item = parentUsers.getJSONObject(key);
                /*item.put("id", item.get("id").toString());
                item.put("member_level", item.get("member_level").toString());*/
                        String memberLevel = item.get("member_level").toString();
                        log.info("memberLevel=====" + memberLevel);
                        int mLevel = 0;
                        if (!isEmpty(memberLevel)) {
                            mLevel = Integer.parseInt(memberLevel);
                        }
                        log.info("mLevel=====" + mLevel);
                        log.info("level=====" + level);
                        log.info("userlevel=====" + user.getLevel());
                        if (user.getLevel() < mLevel) {
                            if (mLevel >= level) {
                                userCommission4vipParentUpdate(user,item, index, commissionSetting,
                                        team_com_map, orderid, amount, team_com_commissionmap, team_com_pjmap, pjSum, product.getLevelAmount(),isSpecialCommission,yxCommissionDetailList,order.getTotalPrice(),topDetail,order);
                                level = mLevel;
                            }
                        }

                        index++;
                    }
                    userMemberLevel4newMainUpdate(main, orderid, singular, isThroughTrain);
                    for (String key : keySet) {
                        //String key = it.next().toString();
                        JSONObject item = parentUsers.getJSONObject(key);
                /*item.put("id", item.get("id").toString());
                item.put("member_level", item.get("member_level").toString());*/
                        userMemberLevel4newUpdate(item, orderid, singular);
                    }
                }
            }
        }

        YxUser mainuser =yxUserService.getById(Long.valueOf(user_id));
        if("yue".equals(payment_id)){
            /*if(!isEmpty(mainMap)){
                String s =mainMap.get("mainSum");
                mainCommissionSum =new BigDecimal(s);
            }*/
            BigDecimal totalPrice =new BigDecimal(payPrice).setScale(2, BigDecimal.ROUND_UP);
            BigDecimal maintotalSum =mainuser.getNowMoney().subtract(totalPrice);
            yxUserService.decPrice(mainuser.getUid(),totalPrice);
            yxUserBillService.expend4commission(mainuser.getUid(),"7", BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_3.getValue(),totalPrice.doubleValue(),maintotalSum.doubleValue(), "积分抵扣",orderid);
        }
        if(!isEmpty(team_com_commissionmap)){
            team_com_commissionmap.forEach((key, value) -> {
                YxUser user =yxUserService.getById(Long.valueOf(key));
                yxUserService.incMoney(user.getUid(),new BigDecimal(value));
                BigDecimal totalSum =user.getNowMoney().add(new BigDecimal(value));
                yxUserBillService.income(user.getUid(),"7", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),new BigDecimal(value).doubleValue(),totalSum.doubleValue(), "订单分润",orderid);
            });
        }

        if(!isEmpty(team_com_pjmap)){
            team_com_pjmap.forEach((key, value) -> {
                YxUser user =yxUserService.getById(Long.valueOf(key));
                yxUserService.incMoney(user.getUid(),new BigDecimal(value));
                BigDecimal totalSum =user.getNowMoney().add(new BigDecimal(value));
                yxUserBillService.income(user.getUid(),"7", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),new BigDecimal(value).doubleValue(),totalSum.doubleValue(), "订单分润",orderid);
            });
        }



        //是否开启赠送活动
        if(product.getIsGiveActivity() ==1){
            if(product.getGiveActivityCount()>0){
                yxUserService.incGiveVip(mainuser.getUid(),product.getGiveActivityCount());
            }
        }



        //生成管理奖
        /*if(topDetail !=null){
                JSONObject jsonLeader=yxUserService.getParentByUserid(mainuser.getUid(),3);
                String parent_id = jsonLeader.getString("parent_id");
            log.info("订单总金额222222222=========="+order.getTotalPrice());
            BigDecimal totalPrice =order.getTotalPrice().setScale(2, BigDecimal.ROUND_UP);
                if(!isEmpty(parent_id)){
                    YxUser leaderUser =yxUserService.getById(Long.valueOf(parent_id));
                    if(topDetail.getManagementAwardSum().compareTo(new BigDecimal("0")) ==1){
                        BigDecimal managementAwardSum =topDetail.getManagementAwardSum().multiply(new BigDecimal("0.01")).multiply(totalPrice);
                        BigDecimal usertotalSum =leaderUser.getNowMoney().add(topDetail.getManagementAwardSum());
                        yxUserService.incMoney(leaderUser.getUid(),managementAwardSum);
                        yxUserService.incBrokeragePrice(managementAwardSum,leaderUser.getUid());
                        yxUserBillService.income(leaderUser.getUid(),"14", BillDetailEnum.CATEGORY_1.getValue(),
                                BillDetailEnum.TYPE_2.getValue(),managementAwardSum.doubleValue(),usertotalSum.doubleValue(), "业绩奖","");
                        log.info(leaderUser.getLevel() + "级用户" + leaderUser.getUid()
                                + "：《业绩奖》" + managementAwardSum + "元");
                    }
                }
        }*/
        //月管理奖
        List<HashMap<String,Object>> userList=yxUserService.getParentByUserId(mainuser.getUid(),3);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        List<MonthlyManagementAwardDetail> detailList = new ArrayList<MonthlyManagementAwardDetail>();
        if(userList.size()>0){
            Date date=new Date();
            String month =df.format(date);
            for(int i=0;i<userList.size();i++){
                Map item = userList.get(i);
                String parentId =item.get("parent_id").toString();
                YxUser user =yxUserService.getById(Long.valueOf(parentId));
                YxUser parentUser =new YxUser();
                if(user.getSpreadUid().longValue() !=0){
                    parentUser =yxUserService.getById(user.getSpreadUid());
                }
                MonthlyManagementAwardDetail detail = new MonthlyManagementAwardDetail();
                detail.setUid(user.getUid());
                detail.setMonth(month);
                detail.setLevel(user.getLevel());
                detail.setNickname(user.getNickname());
                detail.setUserPhone(user.getPhone());
                detail.setHeadimgurl(user.getAvatar());
                detail.setFromUserId(mainuser.getUid());
                detail.setFromUserName(mainuser.getNickname());
                detail.setFromUserPhone(mainuser.getPhone());
                detail.setFromHeadimgurl(mainuser.getAvatar());
                detail.setTotalSum(new BigDecimal(payPrice));
                if(user.getSpreadUid().longValue() !=0) {
                    detail.setParentId(parentUser.getUid());
                    detail.setParentHeadimgurl(parentUser.getAvatar());
                    detail.setParentNickname(parentUser.getNickname());
                    detail.setParentUserPhone(parentUser.getPhone());
                }else{
                    detail.setParentId(Long.valueOf(0));
                }
                detailList.add(detail);
            }
            monthlyManagementAwardDetailService.saveBatch(detailList);
        }
    }



    // vip产品购买者通用分润
    private  void userCommission4vipMainUpdate(JSONObject mainUser, int index, JSONObject commissionSetting,
                                               Map<String, String> team_com_map,String orderid, int amount,
                                               Map<String, String> team_com_commissionmap,
                                               Map<String, String> team_com_pjmap,int pjSum,
                                               Map<String, String> mainMap,int levelAmount,
                                               int isSpecialCommission,List<YxCommissionDetail> yxCommissionDetailList,BigDecimal payPrice,YxCommissionDetail topDetail)
    {
        String mainUserId = mainUser.get("id").toString();
        String main_member_level = mainUser.get("member_level").toString();
        YxUser user = yxUserService.getById(Long.valueOf(mainUserId));

        if (main_member_level.equals("0") ||main_member_level.equals("1")) {
            log.info("普通用户：" + mainUserId + "无分润权限");
            return;
        }
        /*if (isEmpty(vipcount) ||Integer.parseInt(vipcount)<1) {
            System.out.println("用户：" + mainUserId + "未购买299礼包,无分润权限");
            return;
        }*/
        if (!"Y".equals(user.getWhetherVipSlim())) {
            log.info("用户：" + mainUserId + "未购买vip礼包产品,无分润权限");
            return;
        }
        YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                .eq(YxSystemUserLevel::getGrade,user.getLevel()));
        int commissionSum = 0;
        int pj_commissionSum = 0;
        //BigDecimal pj_commissionSum = BigDecimal.ZERO;
        //int pj_sum =5*(amount);
        int pj_sum =pjSum;
        //BigDecimal pj_sum =BigDecimal.ZERO;
        if(ObjectUtil.isNotNull(yxSystemUserLevel)){
            pj_sum =yxSystemUserLevel.getCommissionSum().intValue()*levelAmount;
            //按比例生成业绩奖
            //pj_sum =payPrice.multiply(topDetail.getManagementAwardSum()).multiply(new BigDecimal("0.01")).multiply(yxSystemUserLevel.getCommissionSum()).multiply(new BigDecimal("0.01"));
        }
        YxUser parentUser =new YxUser();
        String hasParent ="N";

        log.info("用户的可用余额NowMoney====="+user.getNowMoney());
        JSONObject jsonObj = yxUserService.getParentByUserid(Long.valueOf(mainUserId),Integer.valueOf(main_member_level));
        //JSONObject jsonObj = userMgr.getParentByUserid(mainUserId,main_member_level);
        System.out.println("11111111111111");
        String parent_id = jsonObj.getString("parent_id");
        String member_id = jsonObj.getString("member_id");
        System.out.println("parent_id用户：" + parent_id+"-------------member_id"+member_id);
        String isSpecial ="N";
        if(!isEmpty(parent_id)){
            hasParent = "Y";
            //new
            parentUser =yxUserService.getById(parent_id);
        }
        for(int i = Integer.parseInt(main_member_level);i>1;i--) {
            if(i == 4 && team_com_map.containsKey("4") && team_com_map.get("4").equals("Y")) {
                System.out.println("只有一次:用户user id+等级：" +user.getUid()+"-----"+ user.getLevel() );
                //commissionSum = 5 * (amount/5);
                pj_commissionSum = 5;
                team_com_map.put("4", "N");
                break;
            }
            if(!team_com_map.containsKey(String.valueOf(i))) {
                commissionSum += (commissionSetting.getInteger(String.valueOf(i)));
                team_com_map.put(String.valueOf(i), "Y");
            }
        }

        if("Y".equals(hasParent)&&commissionSum>0){
            System.out.println("用户user等级：" + user.getLevel().intValue() +"==上级用户parentUser等级"+member_id);
            if("Y".equals(isSpecial)){
                //commissionSum =commissionSum-pj_sum;
                //pj_commissionSum =pj_sum;
                log.info("特殊级别用户user等级是联营公司并且上级是股东：" + user.getLevel().intValue() +"===用户user commissionSum="+commissionSum+"===用户parentUser pj_commissionSum="+pj_commissionSum);
            }else {
                if (user.getLevel().intValue() >= 3 && (user.getLevel().intValue() == Integer.parseInt(member_id))) {
                    //commissionSum = commissionSum - pj_sum;
                    pj_commissionSum = pj_sum;
                    System.out.println("用户user等级>=钻石并且上级是同级：" + user.getLevel().intValue() + "===用户user commissionSum=" + commissionSum + "===用户parentUser pj_commissionSum=" + pj_commissionSum);
                }
            }
        }
        if(commissionSum>0) {
            log.info("commissionSum====="+commissionSum);
            BigDecimal commissionTotalSum =new BigDecimal(commissionSum);
            log.info("commissionTotalSum======"+commissionTotalSum);
            log.info("mainUserId======"+mainUserId);
            log.info("NowMoney======"+user.getNowMoney());
            //team_com_commissionmap.put(parentUser.getUid().toString(), commissionTotalSum.toString());

            if(pj_commissionSum>0) {
                // YxUser parentuser = yxUserService.getById(Long.valueOf(parent_id));
                BigDecimal pj_commissionTotalSum =new BigDecimal(pj_commissionSum);
                System.out.println("pj_commissionTotalSum=================================="+pj_commissionTotalSum);
                if(team_com_pjmap.containsKey(parent_id)) {
                    String s =team_com_pjmap.get(parent_id);
                    BigDecimal tempSum =new BigDecimal(s).add(pj_commissionTotalSum);
                    team_com_pjmap.put(parent_id, tempSum.toString());
                }else{
                    team_com_pjmap.put(parent_id, pj_commissionTotalSum.toString());
                }

            }
        }

    }


    // vip产品购买者上级通用分润
    private  void userCommission4vipParentUpdate(YxUser buyUser,JSONObject mainUser, int index, JSONObject commissionSetting,
                                                 Map<String, String> team_com_map,String orderid,
                                                 int amount,Map<String, String> team_com_commissionmap,
                                                 Map<String, String> team_com_pjmap,int pjSum,int levelAmount,
                                                 int isSpecialCommission,List<YxCommissionDetail> yxCommissionDetailList,BigDecimal payPrice,YxCommissionDetail topDetail,YxStoreOrder order)
    {
        String mainUserId = mainUser.get("id").toString();
        String main_member_level = mainUser.get("member_level").toString();
        YxUser user = yxUserService.getById(Long.valueOf(mainUserId));
        log.info("mainUserId======"+mainUserId);
        log.info("team_com_map1111111111======"+team_com_map);
        //String vipcount = storeOrderCartInfoService.getOrderVIPCountByUserid(Long.valueOf(mainUserId));//检查是否有购买299产品
        //System.out.println("vipcount=======" + vipcount );
        //String main_whether_slim = mainUser.get("whether_slim").toString();
        if (main_member_level.equals("0") ||main_member_level.equals("1")) {
            log.info("普通用户：" + mainUserId + "无分润权限");
            return;
        }
        if (!"Y".equals(user.getWhetherVipSlim())) {
            log.info("用户：" + mainUserId + "未购买vip礼包产品,无分润权限");
            return;
        }
        YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                .eq(YxSystemUserLevel::getGrade,user.getLevel()));
        int commissionSum = 0;
        int pj_commissionSum = 0;
        //BigDecimal pj_commissionSum = BigDecimal.ZERO;
        //int pj_sum =5*(amount);
        int pj_sum =pjSum;
        //BigDecimal pj_sum =BigDecimal.ZERO;
        if(ObjectUtil.isNotNull(yxSystemUserLevel)){
            pj_sum =yxSystemUserLevel.getCommissionSum().intValue()*levelAmount;
            //pj_sum =payPrice.multiply(topDetail.getManagementAwardSum()).multiply(new BigDecimal("0.01")).multiply(yxSystemUserLevel.getCommissionSum()).multiply(new BigDecimal("0.01"));
        }
        YxUser parentUser =new YxUser();
        String hasParent ="N";

        log.info("用户的可用余额NowMoney====="+user.getNowMoney());
        JSONObject jsonObj = yxUserService.getParentByUserid(Long.valueOf(mainUserId),Integer.valueOf(main_member_level));
        //JSONObject jsonObj = userMgr.getParentByUserid(mainUserId,main_member_level);
        System.out.println("11111111111111");
        String parent_id = jsonObj.getString("parent_id");
        String member_id = jsonObj.getString("member_id");
        log.info("parent_id用户：" + parent_id+"-------------member_id"+member_id);
        log.info("buyer用户：" + buyUser.getUid()+"-------------member_id"+member_id+"-------------Spread_id"+buyUser.getSpreadUid());
        String isSpecial ="N";
        if(!isEmpty(parent_id)){
            //股东的平级奖
            /*if(user.getLevel().intValue() ==5){
                if(user.getSpreadUid().intValue() !=0){
                    parentUser =yxUserService.getById(user.getSpreadUid());
                     if(parentUser.getLevel() ==Integer.parseInt(member_id)){
                            hasParent ="Y";
                            parent_id =user.getSpreadUid().toString();
                     }
                }
            }else{
                if(buyUser.getSpreadUid().longValue() ==user.getUid().longValue()){
                    if(user.getSpreadUid().intValue() !=0){
                        parentUser =yxUserService.getById(user.getSpreadUid());
                        if(Integer.parseInt(main_member_level) ==4&&parentUser.getLevel().intValue()==5){
                            hasParent ="Y";
                            parent_id =user.getSpreadUid().toString();
                            isSpecial ="Y";
                        }else {
                            if (parentUser.getLevel() == Integer.parseInt(member_id)) {
                                hasParent = "Y";
                                parent_id = user.getSpreadUid().toString();
                            }
                        }
                    }
                }
            }*/
            hasParent = "Y";
            parentUser =yxUserService.getById(parent_id);

            log.info( "上级parentUser id+等级"+parent_id+"-----"+Integer.parseInt(member_id));
        }
        //System.out.println("用户user Kf_code1111111  team_com_map" +team_com_map.get("6") );
        for(int i = Integer.parseInt(main_member_level);i>1;i--) {
            if(i == 4 && team_com_map.containsKey("4") && team_com_map.get("4").equals("Y")) {
                log.info("只有一次:用户user id+等级：" +user.getUid()+"-----"+ user.getLevel() );
                //commissionSum = 5 * (amount/5);
                pj_commissionSum = 5;
                team_com_map.put("4", "N");
                break;
            }
            if(!team_com_map.containsKey(String.valueOf(i))) {
                commissionSum += (commissionSetting.getInteger(String.valueOf(i)));
                team_com_map.put(String.valueOf(i), "Y");
            }
        }
        /*if(team_com_map.isEmpty()) {
            BigDecimal commissionOrderSum =order.getCommissionSum() !=null?order.getCommissionSum():BigDecimal.ZERO;
            log.info("commissionOrderSum======"+commissionOrderSum);
            if(commissionOrderSum.compareTo(new BigDecimal("0")) ==0){
                commissionSum += (commissionSetting.getInteger(main_member_level));
                team_com_map.put(main_member_level, "Y");
            }
        }*/
        log.info("commissionSum======"+commissionSum);
        log.info("team_com_map222222======"+team_com_map);
        //System.out.println("用户  parentUser22222  user 的commissionSum====" +commissionSum );
        if("Y".equals(hasParent)){
            log.info("用户user等级：" + user.getLevel().intValue() +"==上级用户parentUser等级"+member_id);
            if("Y".equals(isSpecial)){
                //commissionSum =commissionSum-pj_sum;
                pj_commissionSum =pj_sum;
                log.info("特殊级别用户user等级是联营公司并且上级是股东：" + user.getLevel().intValue() +"===用户user commissionSum="+commissionSum+"===用户parentUser pj_commissionSum="+pj_commissionSum);
            }else{
                if(user.getLevel().intValue()>=3&&(user.getLevel().intValue() ==Integer.parseInt(member_id))){
                    //commissionSum =commissionSum-pj_sum;
                    pj_commissionSum =pj_sum;
                    log.info("用户user等级>=钻石并且上级是同级：" + user.getLevel().intValue() +"===用户user commissionSum="+commissionSum+"===用户parentUser pj_commissionSum="+pj_commissionSum);
                }
            }
        }
        //System.out.println("用户 3333====" +commissionSum );
        if(commissionSum>0) {
            log.info("commissionSum====="+commissionSum);
            BigDecimal commissionTotalSum =new BigDecimal(commissionSum);
            log.info("commissionTotalSum======"+commissionTotalSum);

            log.info("NowMoney======"+user.getNowMoney());
            if(team_com_commissionmap.containsKey(mainUserId)) {
                BigDecimal tempSum =new BigDecimal(team_com_commissionmap.get(mainUserId)).add(commissionTotalSum);
                team_com_commissionmap.put(mainUserId, tempSum.toString());
            }else{
                team_com_commissionmap.put(mainUserId, commissionTotalSum.toString());
            }
            if(pj_commissionSum>0) {
                // YxUser parentuser = yxUserService.getById(Long.valueOf(parent_id));
                BigDecimal pj_commissionTotalSum =new BigDecimal(pj_commissionSum);
                System.out.println("pj_commissionTotalSum=================================="+pj_commissionTotalSum);
                if(team_com_pjmap.containsKey(parent_id)) {
                    String s =team_com_pjmap.get(parent_id);
                    BigDecimal tempSum =new BigDecimal(s).add(pj_commissionTotalSum);
                    team_com_pjmap.put(parent_id, tempSum.toString());
                }else{
                    team_com_pjmap.put(parent_id, pj_commissionTotalSum.toString());
                }

            }
            //特殊分润
            if(isSpecialCommission ==1){
                //二代平级奖
                if(!isEmpty(parent_id)){
                    JSONObject json = yxUserService.getParentByUserid(Long.valueOf(parent_id),Integer.valueOf(main_member_level));
                    log.info("二代平级奖开始========");
                    String parentId = json.getString("parent_id");
                    String memberId = json.getString("member_id");
                    log.info("parentId用户：" + parentId+"-------------memberId"+memberId);
                    if(!isEmpty(parentId)){
                        if(yxCommissionDetailList.size()>0){
                            for(YxCommissionDetail detail:yxCommissionDetailList){
                                if(Integer.valueOf(memberId).intValue() ==detail.getLevel()){
                                    if(detail.getSecondProfitSum().compareTo(new BigDecimal(("0"))) ==1){
                                        team_com_pjmap.put(parentId, detail.getSecondProfitSum().toString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        /*if(pj_commissionSum.compareTo(new BigDecimal("0"))==1&&team_com_pjmap.isEmpty()) {
            // YxUser parentuser = yxUserService.getById(Long.valueOf(parent_id));
            //BigDecimal pj_commissionTotalSum =new BigDecimal(pj_commissionSum);
            log.info("pj_commissionSum=================================="+pj_commissionSum);
            team_com_pjmap.put(parent_id, pj_commissionSum.toString());

        }*/

    }


    // 用户级别调整
    private  void userMemberLevel4newUpdate(JSONObject mainUser,String orderid,int orderCount)
    {

        String mainUserId = mainUser.get("id").toString();
        log.info("orderCount====="+orderCount);
        log.info("orderid====="+orderid);
        String countSum = storeOrderCartInfoService.getOrderCountByUserid(Long.valueOf(mainUserId),Long.valueOf(orderid));
        log.info("countSum====="+countSum);
        int count =orderCount +Integer.valueOf(countSum);
        log.info("count====="+count);
        String vipcount = storeOrderCartInfoService.getOrderVIPCountByUserid(Long.valueOf(mainUserId));//检查是否有购买299产品
        String totalSum = storeOrderCartInfoService.getOrderVIPTotalSumByUserid(Long.valueOf(mainUserId));//统计金额
        log.info("totalSum11111====="+totalSum);
        int main_member_level = Integer.parseInt(mainUser.get("member_level")
                .toString());
        String member_id =mainUser.get("member_level")
                .toString();

        YxUser user = yxUserService.getById(Long.valueOf(mainUserId));
        log.info("WhetherVipSlim====="+user.getWhetherVipSlim());
        Integer baseCount =0;
        if(user.getBaseCount() !=null){
            baseCount =user.getBaseCount();
        }
        log.info("baseCount====="+baseCount);
        Integer totalCount =baseCount+count;
        log.info("totalCount====="+totalCount);
        user.setVipCount(totalCount);
        yxUserService.saveOrUpdate(user);
        int updatelevel = 0;
        String isBreak ="N";
        List<YxSystemUserLevel> yxSystemUserLevelList=yxSystemUserLevelService.list(new LambdaQueryWrapper<YxSystemUserLevel>().ge(YxSystemUserLevel ::getGrade,main_member_level).orderByAsc());
        if(yxSystemUserLevelList.size()>0){

            for(int i =0;i<yxSystemUserLevelList.size();i++){
                if("N".equals(isBreak)){
                    YxSystemUserLevel level =yxSystemUserLevelList.get(i);
                    List<YxSystemUserTask> yxSystemUserTaskList=yxSystemUserTaskService.list(new LambdaQueryWrapper<YxSystemUserTask>().eq(YxSystemUserTask ::getLevelId,level.getGrade()));
                    if(yxSystemUserTaskList.size()>0){
                        Integer taskCount =0;
                        for(int j =0;j<yxSystemUserTaskList.size();j++){
                            YxSystemUserTask yst =yxSystemUserTaskList.get(j);
                            if("userVipSlim".equals(yst.getTaskType())){
                                if("Y".equals(user.getWhetherVipSlim())){
                                    taskCount ++;
                                }
                            }else if("upgradeCount".equals(yst.getTaskType())){
                                if(totalCount>=yst.getNumber()){
                                    taskCount ++;
                                }
                            }else if("directlyCount".equals(yst.getTaskType())){
                                String childCount = yxUserService.getChildrens4Main(Long.valueOf(mainUserId),yst.getMaxNumber());//获取当前用户的同级直属人数
                                if(!isEmpty(childCount)&&Integer.parseInt(childCount)>=yst.getNumber()){
                                    taskCount ++;
                                }
                            }else if("totalSum".equals(yst.getTaskType())){
                                if(new BigDecimal(totalSum).compareTo(yst.getTotalSum())==1){
                                    taskCount ++;
                                }
                            }else if("upgradeCrown".equals(yst.getTaskType())){
                                if("Y".equals(user.getIsOpenCrown())){
                                    taskCount ++;
                                }
                            }else if("upgradeLianc".equals(yst.getTaskType())){
                                if("Y".equals(user.getIsOpenLian())){
                                    taskCount ++;
                                }
                            }
                        }
                        if(taskCount>=yxSystemUserTaskList.size()){
                            updatelevel =level.getGrade();
                        }else{
                            isBreak ="Y";
                            break;
                        }
                    }
                }
            }
        }
        log.info("updatelevel====="+updatelevel);
        //if(updatelevel<3){
            if(updatelevel > main_member_level) {
                log.info("用户"+mainUserId +"升级到"+updatelevel);
                yxUserLevelService.changeUserLevel(Long.valueOf(mainUserId),updatelevel);
                //userMgr.changeMember(mainUserId, String.valueOf(updatelevel));
            }
        //}

    }

    // 用户级别调整
    private  void userMemberLevel4newMainUpdate(JSONObject mainUser,String orderid,int orderCount,int isThroughTrain)
    {

        String mainUserId = mainUser.get("id").toString();
        log.info("orderCount====="+orderCount);
        log.info("orderid====="+orderid);
        String countSum = storeOrderCartInfoService.getOrderCountByUserid(Long.valueOf(mainUserId),Long.valueOf(orderid));
        log.info("countSum====="+countSum);
        int count =orderCount +Integer.valueOf(countSum);
        log.info("count====="+count);
        String vipcount = storeOrderCartInfoService.getOrderVIPCountByUserid(Long.valueOf(mainUserId));//检查是否有购买299产品
        String totalSum = storeOrderCartInfoService.getOrderVIPTotalSumByUserid(Long.valueOf(mainUserId));//统计金额
        log.info("totalSum11111====="+totalSum);
        int main_member_level = Integer.parseInt(mainUser.get("member_level")
                .toString());
        String member_id =mainUser.get("member_level")
                .toString();

        //String childCount = yxUserService.getChildrens4Main(Long.valueOf(mainUserId),Integer.valueOf(member_id));//获取当前用户的同级直属人数
        //System.out.println("获取当前用户的同级直属人数"+childCount +"等级"+member_id+"====单数:"+count);
        YxUser user = yxUserService.getById(Long.valueOf(mainUserId));
        log.info("WhetherVipSlim====="+user.getWhetherVipSlim());
        Integer baseCount =0;
        if(user.getBaseCount() !=null){
            baseCount =user.getBaseCount();
        }
        log.info("baseCount====="+baseCount);
        Integer totalCount =baseCount+count;
        log.info("totalCount====="+totalCount);
        user.setVipCount(totalCount);
        yxUserService.saveOrUpdate(user);
        int updatelevel = 0;
        String isBreak ="N";
        List<YxSystemUserLevel> yxSystemUserLevelList=yxSystemUserLevelService.list(new LambdaQueryWrapper<YxSystemUserLevel>().ge(YxSystemUserLevel ::getGrade,main_member_level).orderByAsc());
        if(yxSystemUserLevelList.size()>0){

            for(int i =0;i<yxSystemUserLevelList.size();i++){
                if("N".equals(isBreak)){
                    YxSystemUserLevel level =yxSystemUserLevelList.get(i);
                    List<YxSystemUserTask> yxSystemUserTaskList=yxSystemUserTaskService.list(new LambdaQueryWrapper<YxSystemUserTask>().eq(YxSystemUserTask ::getLevelId,level.getGrade()));
                    if(yxSystemUserTaskList.size()>0){
                        Integer taskCount =0;
                        for(int j =0;j<yxSystemUserTaskList.size();j++){
                            YxSystemUserTask yst =yxSystemUserTaskList.get(j);
                            if("userVipSlim".equals(yst.getTaskType())){
                                if(isThroughTrain !=0){
                                    taskCount ++;
                                }else{
                                    if("Y".equals(user.getWhetherVipSlim())){
                                        taskCount ++;
                                    }
                                }
                            }else if("upgradeCount".equals(yst.getTaskType())){
                                if(isThroughTrain >1){
                                    taskCount ++;
                                }else {
                                    if (totalCount >= yst.getNumber()) {
                                        taskCount++;
                                    }
                                }
                            }else if("directlyCount".equals(yst.getTaskType())){
                                if(isThroughTrain !=0){
                                    taskCount ++;
                                }else{
                                    String childCount = yxUserService.getChildrens4Main(Long.valueOf(mainUserId),yst.getMaxNumber());//获取当前用户的同级直属人数
                                    if(!isEmpty(childCount)&&Integer.parseInt(childCount)>=yst.getNumber()){
                                        taskCount ++;
                                    }
                                }
                            }else if("totalSum".equals(yst.getTaskType())){
                                if(new BigDecimal(totalSum).compareTo(yst.getTotalSum())==1){
                                    taskCount ++;
                                }
                            }else if("upgradeCrown".equals(yst.getTaskType())){
                                if(isThroughTrain ==3){
                                    taskCount ++;
                                }else{
                                    if("Y".equals(user.getIsOpenCrown())){
                                        taskCount ++;
                                    }
                                }
                            }else if("upgradeLianc".equals(yst.getTaskType())){
                                if("Y".equals(user.getIsOpenLian())){
                                    taskCount ++;
                                }
                            }
                        }
                        if(taskCount>=yxSystemUserTaskList.size()){
                            updatelevel =level.getGrade();
                        }else{
                            isBreak ="Y";
                            break;
                        }
                    }
                }
            }
        }
        log.info("updatelevel====="+updatelevel);
        //if(updatelevel<3){
            if(updatelevel > main_member_level) {
                log.info("用户"+mainUserId +"升级到"+updatelevel);
                yxUserLevelService.changeUserLevel(Long.valueOf(mainUserId),updatelevel);
                //userMgr.changeMember(mainUserId, String.valueOf(updatelevel));
            }
        //}

    }





    private  void operateCommissionUpdate(String orderid, BigDecimal provinceBigDecimal,BigDecimal cityBigDecimal,BigDecimal countyBigDecimal)
    {
        YxStoreOrder order =storeOrderService.getById(orderid);
        Integer provinceId =order.getProvinceId();
        Integer cityId =order.getCityId();
        Integer districtId =order.getDistrictId();
        YxSystemCity district =systemCityService.getOne(Wrappers.<YxSystemCity>lambdaQuery()
                .eq(YxSystemCity::getCityId, districtId));
        if(district != null){
            YxUser user = yxUserService.getOne(Wrappers.<YxUser>lambdaQuery()
                    .eq(YxUser::getAreaId, Long.valueOf(districtId)));
            if(user !=null){
                BigDecimal usertotalSum =user.getNowMoney().add(countyBigDecimal);
                yxUserService.incMoney(user.getUid(),countyBigDecimal);
                //yxUserService.incBrokeragePrice(operateBigDecimal,user.getUid());
                yxUserBillService.income(user.getUid(),"12", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),countyBigDecimal.doubleValue(),usertotalSum.doubleValue(), "区级分润",orderid);
                log.info(user.getLevel() + "级用户" + user.getUid()
                        + "：《区级分润》" + countyBigDecimal + "元");
            }
        }
        YxSystemCity city =systemCityService.getOne(Wrappers.<YxSystemCity>lambdaQuery()
                .eq(YxSystemCity::getCityId, cityId));
        if(city != null){
            YxUser user = yxUserService.getOne(Wrappers.<YxUser>lambdaQuery()
                    .eq(YxUser::getAreaId, Long.valueOf(cityId)));
            if(user !=null){
                BigDecimal usertotalSum =user.getNowMoney().add(cityBigDecimal);
                yxUserService.incMoney(user.getUid(),cityBigDecimal);
                //yxUserService.incBrokeragePrice(operateBigDecimal,user.getUid());
                yxUserBillService.income(user.getUid(),"12", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),cityBigDecimal.doubleValue(),usertotalSum.doubleValue(), "市级分润",orderid);
                log.info(user.getLevel() + "级用户" + user.getUid()
                        + "：《市级分润》" + cityBigDecimal + "元");
            }
        }
        YxSystemCity province =systemCityService.getOne(Wrappers.<YxSystemCity>lambdaQuery()
                .eq(YxSystemCity::getCityId, provinceId));
        if(province != null){
            YxUser user = yxUserService.getOne(Wrappers.<YxUser>lambdaQuery()
                    .eq(YxUser::getAreaId, Long.valueOf(provinceId)));
            if(user !=null){
                BigDecimal usertotalSum =user.getNowMoney().add(provinceBigDecimal);
                yxUserService.incMoney(user.getUid(),provinceBigDecimal);
                //yxUserService.incBrokeragePrice(operateBigDecimal,user.getUid());
                yxUserBillService.income(user.getUid(),"12", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),provinceBigDecimal.doubleValue(),usertotalSum.doubleValue(), "省级分润",orderid);
                log.info(user.getLevel() + "级用户" + user.getUid()
                        + "：《省级分润》" + provinceBigDecimal + "元");
            }
        }
        //市级代理
       /* String city =tempAddress[1];
        Area area =new Area();
        List<Area> areaList = systemCityService.list(Wrappers.<Area>lambdaQuery()
                .like(Area::getName, city));
        if(areaList.size()>0){
            area =areaList.get(0);
            List<YxUser> userList = yxUserService.list(Wrappers.<YxUser>lambdaQuery()
                    .like(YxUser::getAreaId, area.getId()));
            if(userList.size()>0){
                YxUser user =userList.get(0);
                //BigDecimal operateBigDecimal =new BigDecimal("2");
                BigDecimal usertotalSum =user.getNowMoney().add(operateBigDecimal);
                yxUserService.incMoney(user.getUid(),operateBigDecimal);
                yxUserService.incBrokeragePrice(operateBigDecimal,user.getUid());
                yxUserBillService.income(user.getUid(),"12", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),operateBigDecimal.doubleValue(),usertotalSum.doubleValue(), "市级分润",orderid);
                System.out.println(user.getLevel() + "级用户" + user.getUid()
                        + "：《市级分润》" + operateBigDecimal + "元");
            }
        }
        //省级代理
        String province =tempAddress[0];
        area =new Area();
        List<Area> areaProvinceList = areaService.list(Wrappers.<Area>lambdaQuery()
                .like(Area::getName, province));
        if(areaProvinceList.size()>0){
            area =areaProvinceList.get(0);
            List<YxUser> userList = yxUserService.list(Wrappers.<YxUser>lambdaQuery()
                    .like(YxUser::getAreaId, area.getId()));
            if(userList.size()>0){
                YxUser user =userList.get(0);
                //BigDecimal operateBigDecimal =new BigDecimal("2");
                BigDecimal usertotalSum =user.getNowMoney().add(operateBigDecimal);
                yxUserService.incMoney(user.getUid(),operateBigDecimal);
                yxUserService.incBrokeragePrice(operateBigDecimal,user.getUid());
                yxUserBillService.income(user.getUid(),"12", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),operateBigDecimal.doubleValue(),usertotalSum.doubleValue(), "省级分润",orderid);
                System.out.println(user.getLevel() + "级用户" + user.getUid()
                        + "：《省级分润》" + operateBigDecimal + "元");
            }
        }*/
    }

    @Transactional
    public void traderMoney(YxUser fromUser,YxUser toUser, BigDecimal traderSum)
    {
        //扣减当前用户余额
        yxUserService.decPrice(fromUser.getUid(),traderSum);
        BigDecimal fromUsertotalSum =fromUser.getNowMoney().subtract(traderSum);
        BigDecimal toUsertotalSum =toUser.getNowMoney().add(traderSum);
        yxUserBillService.expend4traderCommission(fromUser.getUid(),toUser.getUid(),"15", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_3.getValue(),traderSum.doubleValue(),fromUsertotalSum.doubleValue(), "积分转账",toUser.getPhone(), BillEnum.PM_0.getValue());
//增加目标用户余额
        log.info( "目标用户====" + toUser.getUid()
                + "：用户余额:====" + toUser.getNowMoney()
                + "：转账积分:====" + traderSum
                + "元"+ "：用户余额:====" + toUser.getNowMoney() + "元");
        yxUserService.incMoney(toUser.getUid(),traderSum);
        yxUserBillService.expend4traderCommission(toUser.getUid(),fromUser.getUid(),"15", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_2.getValue(),traderSum.doubleValue(),toUsertotalSum.doubleValue(), "转账获取积分",fromUser.getPhone(), BillEnum.PM_1.getValue());

        //yxUserService.incBrokeragePrice(traderSum,toUser.getUid());
    }

    // 推三返一产品分润
    private  void rebateOrderCommission(String user_id, String goods_id,
                                          String combinationId,String orderid) {
        YxUser user = yxUserService.getById(Long.valueOf(user_id));
        YxStoreCombination storeCombination = storeCombinationService.getById(Long.valueOf(combinationId));
        YxUser parentUser = new YxUser();
        BigDecimal rebateBigDecimal =new BigDecimal("0");
        if(user.getSpreadUid() != null && user.getSpreadUid() > 0){
            parentUser =yxUserService.getById(user.getSpreadUid());
            int count =storePinkService.getPinkOk4selfRebateSumTotalNum(user.getSpreadUid(),Long.valueOf(combinationId));
            if(count>0){
                int remainder =count%storeCombination.getPeople();//余数
                if(remainder ==0){
                    rebateBigDecimal =storeCombination.getPrice();
                }else{
                    rebateBigDecimal =storeCombination.getCommissionSum();
                }
            }
            if(rebateBigDecimal.compareTo(new BigDecimal("0")) ==1){
                BigDecimal usertotalSum =parentUser.getNowMoney().add(rebateBigDecimal);
                yxUserService.incMoney(parentUser.getUid(),rebateBigDecimal);
                //yxUserService.incBrokeragePrice(rebateBigDecimal,parentUser.getUid());
                yxUserBillService.income(parentUser.getUid(),"13", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),rebateBigDecimal.doubleValue(),usertotalSum.doubleValue(), "推三返一分润",orderid);
                log.info(parentUser.getLevel() + "级用户" + parentUser.getUid()
                        + "：《推三返一分润》" + rebateBigDecimal + "元");
            }
        }
    }

    // 余额支付推三返一产品分润
    private  void yueRebateOrderCommission(String user_id, String goods_id,
                                        String combinationId,String orderid) {
        YxUser user = yxUserService.getById(Long.valueOf(user_id));
        YxStoreCombination storeCombination = storeCombinationService.getById(Long.valueOf(combinationId));
        yxUserBillService.expend4commission(Long.parseLong(user_id),"7", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_3.getValue(),storeCombination.getPrice().doubleValue(),user.getNowMoney().doubleValue(), "积分抵扣",orderid);
        yxUserService.decPrice(Long.parseLong(user_id),storeCombination.getPrice());
        log.info(user.getLevel() + "级用户" + user_id
                + "：《积分抵扣》" + storeCombination.getPrice().multiply(new BigDecimal(-1)) + "元");
        YxUser parentUser = new YxUser();
        BigDecimal rebateBigDecimal =new BigDecimal("0");
        if(user.getSpreadUid() != null && user.getSpreadUid() > 0){
            parentUser =yxUserService.getById(user.getSpreadUid());
            int count =storePinkService.getPinkOk4selfRebateSumTotalNum(user.getSpreadUid(),Long.valueOf(combinationId));
            if(count>0){
                int remainder =count%storeCombination.getPeople();//余数
                if(remainder ==0){
                    rebateBigDecimal =storeCombination.getPrice();
                }else{
                    rebateBigDecimal =storeCombination.getCommissionSum();
                }
            }
            if(rebateBigDecimal.compareTo(new BigDecimal("0")) ==1){
                BigDecimal usertotalSum =parentUser.getNowMoney().add(rebateBigDecimal);
                yxUserService.incMoney(parentUser.getUid(),rebateBigDecimal);
                //yxUserService.incBrokeragePrice(rebateBigDecimal,parentUser.getUid());
                yxUserBillService.income(parentUser.getUid(),"13", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),rebateBigDecimal.doubleValue(),usertotalSum.doubleValue(), "推三返一分润",orderid);
                log.info(parentUser.getLevel() + "级用户" + parentUser.getUid()
                        + "：《推三返一分润》" + rebateBigDecimal + "元");
            }
        }
    }

    // 秒杀产品分润
    private  void seckillOrderCommission(String user_id, String goods_id,
                                        String seckillId,String orderid,int amount) {
        YxUser user = yxUserService.getById(Long.valueOf(user_id));
        YxStoreSeckill storeSeckill = yxStoreSeckillService.getById(Long.valueOf(seckillId));
        YxUser parentUser = new YxUser();
        BigDecimal seckillBigDecimal =new BigDecimal("0");
        if(user.getSpreadUid() != null && user.getSpreadUid() > 0){
            parentUser =yxUserService.getById(user.getSpreadUid());
            seckillBigDecimal =storeSeckill.getCommissionSum().multiply(new BigDecimal(amount));
            if(seckillBigDecimal.compareTo(new BigDecimal("0")) ==1){
                BigDecimal usertotalSum =parentUser.getNowMoney().add(seckillBigDecimal);
                yxUserService.incMoney(parentUser.getUid(),seckillBigDecimal);
                //yxUserService.incBrokeragePrice(seckillBigDecimal,parentUser.getUid());
                yxUserBillService.income(parentUser.getUid(),"16", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),seckillBigDecimal.doubleValue(),usertotalSum.doubleValue(), "秒杀分润",orderid);
                System.out.println(parentUser.getLevel() + "级用户" + parentUser.getUid()
                        + "：《秒杀分润》" + seckillBigDecimal + "元");
            }
        }
    }

    // 余额支付秒杀产品分润
    private  void yueSeckillOrderCommission(String user_id, String goods_id,
                                           String seckillId,String orderid,int amount) {
        YxUser user = yxUserService.getById(Long.valueOf(user_id));
        YxStoreSeckill storeSeckill = yxStoreSeckillService.getById(Long.valueOf(seckillId));
        yxUserBillService.expend4commission(Long.parseLong(user_id),"7", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_3.getValue(),storeSeckill.getPrice().multiply(new BigDecimal(amount)).doubleValue(),user.getNowMoney().doubleValue(), "积分抵扣",orderid);
        yxUserService.incMoney(Long.parseLong(user_id),storeSeckill.getPrice().multiply(new BigDecimal(amount)).multiply(new BigDecimal(-1)));
        System.out.println(user.getLevel() + "级用户" + user_id
                + "：《积分抵扣》" + storeSeckill.getPrice().multiply(new BigDecimal(-1)) + "元");
        YxUser parentUser = new YxUser();
        BigDecimal seckillBigDecimal =new BigDecimal("0");
        if(user.getSpreadUid() != null && user.getSpreadUid() > 0){
            parentUser =yxUserService.getById(user.getSpreadUid());
            seckillBigDecimal =storeSeckill.getCommissionSum().multiply(new BigDecimal(amount));
            if(seckillBigDecimal.compareTo(new BigDecimal("0")) ==1){
                BigDecimal usertotalSum =parentUser.getNowMoney().add(seckillBigDecimal);
                yxUserService.incMoney(parentUser.getUid(),seckillBigDecimal);
                //yxUserService.incBrokeragePrice(seckillBigDecimal,parentUser.getUid());
                yxUserBillService.income(parentUser.getUid(),"16", BillDetailEnum.CATEGORY_1.getValue(),
                        BillDetailEnum.TYPE_2.getValue(),seckillBigDecimal.doubleValue(),usertotalSum.doubleValue(), "秒杀分润",orderid);
                System.out.println(parentUser.getLevel() + "级用户" + parentUser.getUid()
                        + "：《秒杀分润》" + seckillBigDecimal + "元");
            }
        }
    }

    public  BigDecimal orderCommission4main(Long user_id, Long goods_id,int amount) {
        //YxUser user = yxUserService.getById(user_id);
        YxStoreProduct product =productService.getById(goods_id);
        JSONObject commissionSetting = new JSONObject();// 分润配置
        BigDecimal commissionSum =new BigDecimal("0");
        Map<String, String> mainMap = new HashMap();//购买者分润金额集合
        List<YxCommissionDetail> yxCommissionDetailList=yxCommissionDetailService.list(new LambdaQueryWrapper<YxCommissionDetail>().eq(YxCommissionDetail ::getCommissionTypeId,product.getCommissionTypeId()));
        if(yxCommissionDetailList.size()>0){
            for(int i =0;i<yxCommissionDetailList.size();i++){
                YxCommissionDetail detail =yxCommissionDetailList.get(i);
                commissionSetting.put(detail.getLevel().toString(),detail.getValue().toString());
            }
        }
        Integer userLevel =0;
        for(int i=0;i<amount;i++){
            int singular =product.getSingular();
            YxUser user = yxUserService.getById(user_id);
            if(userLevel ==0){
                userLevel =user.getLevel();
            }
            userCommission4estimateUpdate(user, commissionSetting,mainMap,product.getLevelAmount(),userLevel);
            userLevel =userMemberLevel4estimateUpdate(user, singular,product.getIsThroughTrain(),userLevel);
        }
        if(!isEmpty(mainMap)){
            String s =mainMap.get("mainSum");
            commissionSum =new BigDecimal(s);
        }
        return commissionSum;
    }

    // 购买者预估分润
    private  void userCommission4estimateUpdate(YxUser mainUser,
                                                JSONObject commissionSetting,Map<String, String> mainMap,int levelAmount,Integer userLevel)
    {
        Long mainUserId = mainUser.getUid();
        Integer main_member_level = userLevel;
        YxUser user = yxUserService.getById(Long.valueOf(mainUserId));

        if (main_member_level==0 ||main_member_level==1) {
            System.out.println("普通用户：" + mainUserId + "无分润权限");
            return;
        }
        if (!"Y".equals(user.getWhetherVipSlim())) {
            System.out.println("用户：" + mainUserId + "未购买vip礼包产品,无分润权限");
            return;
        }
        YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                .eq(YxSystemUserLevel::getGrade,main_member_level));
        int commissionSum = 0;
        BigDecimal pj_commissionSum = BigDecimal.ZERO;
        //int pj_sum =5*(amount);
        //int pj_sum =pjSum;
        BigDecimal pj_sum =BigDecimal.ZERO;

        YxUser parentUser =new YxUser();
        String hasParent ="N";
        log.info("用户的可用余额NowMoney====="+user.getNowMoney());
        JSONObject jsonObj = yxUserService.getParentByUserid(Long.valueOf(mainUserId),Integer.valueOf(main_member_level));
        //JSONObject jsonObj = userMgr.getParentByUserid(mainUserId,main_member_level);
        System.out.println("11111111111111");
        String parent_id = jsonObj.getString("parent_id");
        String member_id = jsonObj.getString("member_id");
        log.info("parent_id用户：" + parent_id+"-------------member_id"+member_id);
        if(!isEmpty(parent_id)){
            if(user.getSpreadUid().intValue() !=0){
                parentUser =yxUserService.getById(user.getSpreadUid());
                if(parentUser.getLevel() <=Integer.parseInt(member_id)){
                    hasParent ="Y";
                }
            }
            parentUser =yxUserService.getById(parent_id);
            //commissionSum += (commissionSetting.getInteger(String.valueOf(main_member_level)));

            log.info( "上级parentUser id+等级"+parent_id+"-----"+Integer.parseInt(member_id));
        }

        for(int i = main_member_level;i>1;i--) {
            commissionSum += (commissionSetting.getInteger(String.valueOf(i)));
        }
        /*if("Y".equals(hasParent)&&commissionSum>0){
            log.info("用户user等级：" + main_member_level +"==上级用户parentUser等级"+member_id);
            if(main_member_level>=3&&(main_member_level ==Integer.parseInt(member_id))){
                commissionSum =commissionSum-pj_sum;
                log.info("用户user等级>=钻石并且上级是同级：" + user.getLevel().intValue() +"===用户user commissionSum="+commissionSum+"===用户parentUser pj_commissionSum="+pj_commissionSum);
            }
        }*/
        if(commissionSum>0) {
            log.info("commissionSum====="+commissionSum);
            BigDecimal commissionTotalSum =new BigDecimal(commissionSum);
            log.info("commissionTotalSum======"+commissionTotalSum);
            log.info("mainUserId======"+mainUserId);
            log.info("NowMoney======"+user.getNowMoney());
            if(mainMap.containsKey("mainSum")) {
                String s =mainMap.get("mainSum");
                BigDecimal tempSum =new BigDecimal(s).add(commissionTotalSum);
                mainMap.put("mainSum", tempSum.toString());
            }else{
                mainMap.put("mainSum", commissionTotalSum.toString());
            }

        }

    }


    // 购买订单预估用户级别
    private  Integer userMemberLevel4estimateUpdate(YxUser mainUser,int orderCount,int isThroughTrain,int userLevel)
    {

        Long mainUserId = mainUser.getUid();
        log.info("orderCount====="+orderCount);
        String countSum = storeOrderCartInfoService.getOrderCountByUserid(mainUserId,Long.valueOf(0));
        log.info("countSum====="+countSum);
        int count =orderCount +Integer.valueOf(countSum);
        log.info("count====="+count);
        int main_member_level = userLevel;
        String totalSum = storeOrderCartInfoService.getOrderVIPTotalSumByUserid(Long.valueOf(mainUserId));//统计金额

        //String childCount = yxUserService.getChildrens4Main(Long.valueOf(mainUserId),Integer.valueOf(member_id));//获取当前用户的同级直属人数
        //System.out.println("获取当前用户的同级直属人数"+childCount +"等级"+member_id+"====单数:"+count);
        YxUser user = yxUserService.getById(mainUserId);
        log.info("WhetherVipSlim====="+user.getWhetherVipSlim());
        Integer baseCount =0;
        if(user.getBaseCount() !=null){
            baseCount =user.getBaseCount();
        }
        log.info("baseCount====="+baseCount);
        Integer totalCount =baseCount+count;
        log.info("totalCount====="+totalCount);
        user.setVipCount(totalCount);
        yxUserService.saveOrUpdate(user);
        int updatelevel = userLevel;
        String isBreak ="N";
        List<YxSystemUserLevel> yxSystemUserLevelList=yxSystemUserLevelService.list(new LambdaQueryWrapper<YxSystemUserLevel>().ge(YxSystemUserLevel ::getGrade,main_member_level).orderByAsc());
        if(yxSystemUserLevelList.size()>0){

            for(int i =0;i<yxSystemUserLevelList.size();i++){
                if("N".equals(isBreak)){
                    YxSystemUserLevel level =yxSystemUserLevelList.get(i);
                    List<YxSystemUserTask> yxSystemUserTaskList=yxSystemUserTaskService.list(new LambdaQueryWrapper<YxSystemUserTask>().eq(YxSystemUserTask ::getLevelId,level.getGrade()));
                    if(yxSystemUserTaskList.size()>0){
                        Integer taskCount =0;
                        for(int j =0;j<yxSystemUserTaskList.size();j++){
                            YxSystemUserTask yst =yxSystemUserTaskList.get(j);
                            if("userVipSlim".equals(yst.getTaskType())){
                                if(isThroughTrain !=0){
                                    taskCount ++;
                                }else{
                                    if("Y".equals(user.getWhetherVipSlim())){
                                        taskCount ++;
                                    }
                                }
                            }else if("upgradeCount".equals(yst.getTaskType())){
                                if(totalCount>=yst.getNumber()){
                                    taskCount ++;
                                }
                            }else if("directlyCount".equals(yst.getTaskType())){
                                if(isThroughTrain !=0){
                                    taskCount ++;
                                }else{
                                    String childCount = yxUserService.getChildrens4Main(Long.valueOf(mainUserId),yst.getMaxNumber());//获取当前用户的同级直属人数
                                    if(!isEmpty(childCount)&&Integer.parseInt(childCount)>=yst.getNumber()){
                                        taskCount ++;
                                    }
                                }
                            }else if("totalSum".equals(yst.getTaskType())){
                                if(new BigDecimal(totalSum).compareTo(yst.getTotalSum())==1){
                                    taskCount ++;
                                }
                            }else if("upgradeCrown".equals(yst.getTaskType())){
                                if(isThroughTrain ==3){
                                    taskCount ++;
                                }else{
                                    if("Y".equals(user.getIsOpenCrown())){
                                        taskCount ++;
                                    }
                                }
                            }else if("upgradeLianc".equals(yst.getTaskType())){
                                if("Y".equals(user.getIsOpenLian())){
                                    taskCount ++;
                                }
                            }
                        }
                        if(taskCount>=yxSystemUserTaskList.size()){
                            updatelevel =level.getGrade();
                        }else{
                            isBreak ="Y";
                            break;
                        }
                    }
                }
            }
        }
        return updatelevel;
    }

    /**
     * 判断对象是否为空（包括空指针、空字符串、空集合）
     *
     * @param obj
     *          需要判断的对象
     * @return true：对象为空；false：对象不为空。
     */
    public static boolean isEmpty(Object obj) {
        if (obj instanceof String) {
            String s = (String) obj;
            if ((s == null) || s.trim().length() == 0) {
                return true;
            }
        } else if (obj instanceof Collection) {
            if (obj == null || ((Collection) obj).size() == 0)
                return true;
        } else if (obj instanceof Map) {
            if (obj == null || ((Map) obj).size() == 0)
                return true;
        } else if (obj == null) {
            return true;
        }
        return false;
    }
}
